package common.web.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import common.constant.LoginConst;


/**
 * 登陆过滤器
 * 
 */
public class LoginFilter implements Filter {
	public static final String ERROR = "ERROR";
	public static final String ERROR_SESSION_NULL = "用户登陆超时";// session过期
	public static final String ERROR_SESSION_USERTYPE = "用户权限不够";// 用户类型
	public static final String ERROR_NOT_LOGIN = "用户还没有进行登陆";// 没有登陆

	protected FilterConfig filterConfig = null;
	protected String[] sysFilterURL = null;// 系统过滤URL
	protected String[] userFilterURL = null;// 会员用户过滤URL

	public void init(FilterConfig arg0) throws ServletException {
		this.filterConfig = arg0;
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String url = req.getRequestURI();
		if(url.indexOf("codeImage.jsp") != -1 || url.indexOf("/static") != -1 || url.indexOf("/frontpage") != -1) {
			chain.doFilter(request, response);
			return;
		}
		
		if (req.getSession(false) == null) {// session过期
			req.getRequestDispatcher("/admin/login.jsp").forward(request,response);
			return;
		}
		
		@SuppressWarnings("unchecked")
		Map<String,Object> loginMap = (Map<String,Object>) req.getSession().getAttribute(LoginConst.SESSION_USER);
		if (loginMap == null) {//没有登陆
			req.getRequestDispatcher("/admin/login.jsp").forward(request,response);
			return;
		}
		
		chain.doFilter(request, response);

	}

	public void destroy() {
		this.filterConfig = null;
		this.sysFilterURL = null;
		this.userFilterURL = null;
	}

}
